import time
from time import sleep

import usb2IIC.usb2iic as i2c
import luinit

dev = luinit.init()
iic_config = i2c.IIC_CONFIG(400000, 1, 7, 1)
ret = i2c.IIC_Init(dev, 0, i2c.byref(iic_config))
print(ret)
# 扫描IIC总线上能正常应答的设备
SlaveAddr = (i2c.c_ushort * 128)()
SlaveAddrNum = i2c.IIC_GetSlaveAddr(dev, 0, i2c.byref(SlaveAddr))


if SlaveAddrNum <= 0:
    print("Get iic address faild!")
    exit()
else:
    print("Get iic address sunccess!")
    print("IIC addr:")
    for i in range(0, SlaveAddrNum):
        print("%02X " % SlaveAddr[i], end='')
    print("")
    # 向0x地址开始写数据
# WriteBuffer[1] = 0
# WriteBuffer[2] = 0
# WriteBuffer[3] = 0
# WriteBuffer[4] = 0
# WriteBuffer[5] = 0
# WriteBuffer[6] = 0
# WriteBuffer[7] = 0
# WriteBuffer[0] = 0x90
# ReadBuffer[0] = 0
# for i in range(0, 8):
#     WriteBuffer[1 + i] = i

# print('len:',len(WriteBuffer))
WriteBuffer = (i2c.c_byte * 1)()
ReadBuffer = (i2c.c_byte * 3)()
while True:
    # 写操作地址90
    WriteBuffer[0] = 0x90
    ret = i2c.IIC_WriteBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 8, 100)
    if ret != i2c.IIC_SUCCESS:
        print(f"Write iic faild! on write {WriteBuffer[0]}")
        exit()
    else:
        # print(f"Write iic {WriteBuffer[0]} sunccess!")
        time.sleep(0.2)

    # 选择通道 00:可调电阻 01:光敏电阻 02:热敏电阻
    WriteBuffer[0] = 0x01
    ret = i2c.IIC_WriteBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 8, 100)
    if ret != i2c.IIC_SUCCESS:
        print(f"Write iic faild! on write {WriteBuffer[0]}")
        exit()
    else:
        # print(f"Write iic {WriteBuffer[0]} sunccess!")
        time.sleep(0.2)
    # 从0x地址开始读取8字节数据
    # WriteBuffer = 0x01
    WriteBuffer[0] = 0x91
    ret = i2c.IIC_WriteReadBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 1, i2c.byref(ReadBuffer), len(ReadBuffer), 100)
    # ret = i2c.IIC_WriteReadBytes(dev, 0, 0x48, i2c.byref(WriteBuffer), 1, i2c.byref(ReadBuffer), 1, 100)
    if ret != i2c.IIC_SUCCESS:
        print("WriteRead iic faild! on write read")
        exit()
    else:
        # print("WriteRead iic sunccess!")
        # print(f"Read Data:{sum(ReadBuffer)/len(ReadBuffer)}")
        print(f"Read Data:{sum(ReadBuffer)}")
        for i in range(0, len(ReadBuffer)):
            # print("%02X " % ReadBuffer[i], end='')
            print( ReadBuffer[i], end=' ')
        print("")
        sleep(0.2)
    # sleep(1)
# Close device
ret = i2c.USB_CloseDevice(dev)
if (bool(ret)):
    print("Close device success!")
else:
    print("Close device faild!")
    exit()
